/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mahumLogs.beans;

import com.mahumLogs.backedbeans.Etudiant;
import com.mahumLogs.backedbeans.Machine;
import com.mahumLogs.backedbeans.TopSite;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import javax.annotation.Resource;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;

/**
 *
 * @author Kalast
 */

@Named
@SessionScoped
public class TopSitesBean implements Serializable{
    
    public static class EtudiantVisites{
        public String nom = "???";
        public String prenom = "???";
        public long id = -1;
        public int visites;
        public String ip;

        public String getNom() {
            return nom;
        }

        public String getPrenom() {
            return prenom;
        }

        public long getId() {
            return id;
        }

        public int getVisites() {
            return visites;
        }

        public String getIp() {
            return ip;
        }
    }
    
    @Inject 
    private LogsBean logsBean;
    
    @PersistenceContext
    private EntityManager em;
    
    @Resource
    private UserTransaction tx;
    
    private List<TopSite> topsite;
    private String domainSelected;
    private TopSite generalTopSite;
    
    private ArrayList<EtudiantVisites> listEtudiantsVisites;

    public TopSitesBean() {
        topsite = new ArrayList();
        listEtudiantsVisites = new ArrayList();
        domainSelected = "google.com";
    }

    public String getDomainSelected() {
        return domainSelected;
    }

    public TopSite getGeneralTopSite() {
        return generalTopSite;
    }

    public void setGeneralTopSite(TopSite generalTopSite) {
        this.generalTopSite = generalTopSite;
    }

    public void setDomainSelected(String domainSelected) {
        this.domainSelected = domainSelected;
        this.viewSite();
        this.majGeneralSite();
    }

    public List<EtudiantVisites> getListEtudiantsVisites() {
        System.err.println("On recupere " + listEtudiantsVisites.size());
        return listEtudiantsVisites;
    }
    
    public void loadGeneral(){
        this.topsite.clear();
    }
    
    public void majGeneralSite(){
        if(this.domainSelected != null){
            try{
                this.generalTopSite = (TopSite) this.em.createQuery("SELECT ts FROM TopSite ts WHERE ts.domaine LIKE :dom").setParameter("dom", this.domainSelected).setMaxResults(1).getSingleResult();
            } catch(Exception ex){
                
            }
        }
    }
    
    public void viewSite(){
        String query = "SELECT l.DOMAINE, e.PRENOM, e.NOM, l.IP, COUNT(l.IP) FROM log l\n" +
"JOIN machine m ON m.IP LIKE l.IP\n" +
"JOIN etudiant e ON e.IDPERSONNE = m.FK_ETUDIANT\n" +
"WHERE l.DOMAINE LIKE 'google.com'\n" +
"GROUP BY l.IP";
        
        System.out.println("query = " + "SELECT e.IDPERSONNE, e.PRENOM, e.NOM, COUNT(l.IP) FROM log l" +
                                        " LEFT JOIN machine m ON m.IP LIKE l.IP" +
                                        " LEFT JOIN etudiant e ON e.IDPERSONNE = m.FK_ETUDIANT" +
                                        " WHERE l.DOMAINE LIKE '" + this.domainSelected + "'" +
                                        " AND l.TIME BETWEEN " + logsBean.getTimeStartSelected() + " AND " + logsBean.getTimeEndSelected() +
                                        " GROUP BY l.IP" + 
                                        " ORDER BY COUNT(l.IP) DESC");
        
        if(domainSelected != null){
            List<Object[]> list = (List<Object[]>)this.em.createNativeQuery("SELECT e.IDPERSONNE, e.PRENOM, e.NOM, COUNT(l.IP), l.IP FROM log l" +
                                        " LEFT JOIN machine m ON m.IP LIKE l.IP" +
                                        " LEFT JOIN etudiant e ON e.IDPERSONNE = m.FK_ETUDIANT" +
                                        " WHERE l.DOMAINE LIKE '" + this.domainSelected + "'" +
                                        " AND l.TIME BETWEEN " + logsBean.getTimeStartSelected() + " AND " + logsBean.getTimeEndSelected() +
                                        " GROUP BY l.IP" + 
                                        " ORDER BY COUNT(l.IP) DESC").getResultList();
                                                
            System.out.println("On trouve une liste de " + list.size());
            EtudiantVisites ev;
            this.listEtudiantsVisites.clear();
            for(Object[] objects : list){
                ev = new EtudiantVisites();
                if(objects[0] != null){
                    ev.id = Integer.valueOf(objects[0].toString());
                }
                if(objects[1] != null){
                    ev.prenom = objects[1].toString();
                }
                if(objects[2] != null){
                    ev.nom = objects[2].toString();
                }
                ev.visites = Integer.valueOf(objects[3].toString());
                ev.ip = objects[4].toString();
                System.out.println("Rempli " + ev.nom + " " + ev.prenom + " " + ev.visites);
                this.listEtudiantsVisites.add(ev);
            }
        }
    }
    
    public void majTopSite(){
        GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris"));
        cal.set(Calendar.YEAR, logsBean.getYearSelected());
        cal.set(Calendar.MONTH, logsBean.getMonthSelected()-1);
        cal.set(Calendar.DATE, logsBean.getDaySelected());
        cal.set(Calendar.HOUR_OF_DAY, logsBean.getHourSelected());
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        
        GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris"));
        cal2.set(Calendar.YEAR, logsBean.getYearSelected());
        cal2.set(Calendar.MONTH, logsBean.getMonthSelected()-1);
        cal2.set(Calendar.DATE, logsBean.getDaySelected());
        cal2.set(Calendar.HOUR_OF_DAY, logsBean.getHourSelected());
        cal2.set(Calendar.MINUTE, 59);
        cal2.set(Calendar.SECOND, 59);
        cal2.set(Calendar.MILLISECOND, 999);
        if(logsBean.getHourSelected() >= 0){
            this.topsite = this.em.createQuery("SELECT t FROM TopSite t WHERE t.annee=:loga AND t.mois=:logm AND t.jour=:logj AND t.heure=:logh GROUP BY t.domaine ORDER BY t.visites DESC")
                .setParameter("loga", logsBean.getYearSelected())
                .setParameter("logm", logsBean.getMonthSelected())
                .setParameter("logj", logsBean.getDaySelected())
                .setParameter("logh", logsBean.getHourSelected())
                .getResultList();
        } else {
            List<Object[]> results = (List<Object[]>) this.em.createQuery("SELECT t.domaine, SUM(t.visites), SUM(t.dataSize) FROM TopSite t WHERE t.annee=:loga AND t.mois=:logm AND t.jour=:logj GROUP BY t.domaine ORDER BY SUM(t.visites) DESC")
                .setParameter("loga", logsBean.getYearSelected())
                .setParameter("logm", logsBean.getMonthSelected())
                .setParameter("logj", logsBean.getDaySelected())
                .getResultList();
            topsite.clear();
            TopSite ts;
            for (Object[] objects : results) {
                ts = new TopSite();
                if(objects[0] != null){
                    ts.setDomaine(objects[0].toString());
                } else {
                    System.err.println("objects[0] = null");
                    continue;
                }
                if(objects[1] != null){
                    
                    ts.setVisites(Integer.valueOf(objects[1].toString()));
                } else {
                    System.err.println("objects[1] = null");
                    continue;
                }
                if(objects[2] != null){
                    ts.setDataSize(Long.valueOf(objects[2].toString()));
                } else {
                    System.err.println("objects[2] = null");
                    continue;
                }
                topsite.add(ts);
            }
        }
    }
    
    public List<TopSite> getTopsite() {
        return topsite;
    }
    
    public String convertDataSize(TopSite ts){
        String[] sufs = new String[]{"o", "Ko", "Mo", "Go"};
        int index = 0;
        double size = ts.getDataSize();
        DecimalFormat df = new DecimalFormat("#.##");

        while (size >= 1000d) {
            index++;
            size /= 1000d;
        }

        return df.format(size) + " " + sufs[index];
    }
}
